package com.androidme.app.framework.base;

import android.util.Log;
import com.androidme.app.framework.util.HttpUtils;

import java.io.File;
import java.io.IOException;

public abstract class AndroidMeDownloadTask implements Runnable {
    private File file;
    private String uri;
    private String ctxName;

    public AndroidMeDownloadTask(String ctxName, File file, String uri) {
        this.file = file;
        this.uri = uri;
        this.ctxName = ctxName;
    }

    @Override
    public void run() {
        onStart();
        try {
            if (AndroidMeActivity.application.containActiveContext(ctxName)) {
                if (HttpUtils.download(file, uri)) {
                    if (AndroidMeActivity.application.containActiveContext(ctxName)) {
                        onSuccess();
                    }
                } else {
                    if (AndroidMeActivity.application.containActiveContext(ctxName)) {
                        onFailure();
                    }
                }
            }
        } catch (IOException ioe) {
            Log.e(getClass().getName(), "http connect error!", ioe);
             if (AndroidMeActivity.application.containActiveContext(ctxName)) {
                 onHTTPException();
             }
        } catch (AndroidMeException he) {
            Log.e(getClass().getName(), "http response error!", he);
             if (AndroidMeActivity.application.containActiveContext(ctxName)) {
                 onHttpResponseError(he.getStatusCode());
             }
        }
    }

    protected abstract void onHTTPException();

    protected abstract void onHttpResponseError(int statusCode);

    protected abstract void onSuccess();

    protected abstract void onFailure();

    protected abstract void onStart();
}
